package com.mh.controller;

import cn.hutool.json.JSONObject;
import com.mh.dto.R;
import com.mh.model.WxPayJsApiPreVO;
import com.mh.utils.WxPayJsApiHttpUtil;
import com.mh.utils.WxPayJsApiNotifyUtil;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;

/**
 * Date:2023/9/5
 * author:zmh
 * description:支付相关接口
 **/

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/pay")
@RequiredArgsConstructor(onConstructor = @__(@Autowired)) // 自动注入
public class PayController {

    private final WxPayJsApiHttpUtil wxPayJsApiHttpUtil;
    private final WxPayJsApiNotifyUtil wxPayJsApiNotifyUtil;

    /**
     * 向微信服务器创建预支付订单
     * @param total 支付金额
     * @return ·
     * @throws Exception ·
     */
    @GetMapping("/preOrderCreate")
    public R<WxPayJsApiPreVO> preOrderCreate(Integer total) throws Exception {
        // 下单操作，并返回前端调用requestPayment函数所需的参数
        WxPayJsApiPreVO wxPayJsApiPreVO = wxPayJsApiHttpUtil.jsApiV3(total);
        return R.success(wxPayJsApiPreVO);
    }

    /**
     * 查单
     */
    @GetMapping("/queryJsApiOrderInfo")
    public R<JSONObject> queryJsApiOrderInfo(@RequestParam("transactionId") String transactionId) throws URISyntaxException, GeneralSecurityException, IOException, NotFoundException, HttpCodeException {
        JSONObject jsonObject = wxPayJsApiHttpUtil.queryJsApiOrderInfoV3(transactionId);
        return R.success(jsonObject);
    }

    /**
     * 成功回调
     */
    @PostMapping("/notify")
    public void wxPayResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 微信回调此函数，取出微信支付订单号，后续可用于查单
        wxPayJsApiNotifyUtil.notifyV3(request, response);
    }

}
